package zl.ordermanager.interceptor;

import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import zl.ordermanager.utils.ConfigUtil;
import zl.ordermanager.utils.ServerInfo;
import zl.ordermanager.vo.SessionInfo;

public class LoginHanlerInterceptor extends HandlerInterceptorAdapter {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoginHanlerInterceptor.class);

	private List<String> excludeUrls;// 不需要拦截的资源

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	private String loginUrl;

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {

		String requestUri = req.getRequestURI();
		String contextPath = req.getContextPath();
		String url = requestUri.substring(contextPath.length());

		if (logger.isInfoEnabled()) {
			logger.info("preHandle(HttpServletRequest, HttpServletResponse, Object) - String url=" + url);
		}

		// 1、请求到登录页面 放行
		for (String excludeUrl : excludeUrls) {
			if (url.startsWith(excludeUrl)) {
				return true;
			}
		}

		// 2、如果用户已经登录 放行
		SessionInfo sessionInfo = (SessionInfo) req.getSession().getAttribute(ConfigUtil.getSessionInfoName());
		if (sessionInfo != null) {
			// 更好的实现方式的使用cookie
			return true;
		}

		// 3、非法请求 即这些请求需要登录后才能访问
		// 重定向到登录页面
		HttpServletResponse response = (HttpServletResponse) res;
		HttpServletRequest request = (HttpServletRequest) req;

		if (ServerInfo.isAjax(request) || request.getParameter("ajax") != null) {
			PrintWriter out = response.getWriter();
			Map<String, String> resultMap = new HashMap<String, String>();
			resultMap.put("statusCode", "301");
			resultMap.put("message", "登录超时，请重新登录！");
			out.println(JSON.toJSONString(resultMap, SerializerFeature.BrowserCompatible));
		} else {
			response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + loginUrl));
		}

		return false;
	}

}
